<?php

class ControllerStartupStartup extends Controller
{
    public function index()
    {
        // Store
        $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "store` WHERE REPLACE(`url`, 'www.', '') = '" . $this->db->escape(($this->request->server['HTTPS'] ? 'https://' : 'http://') . str_replace('www.', '', $_SERVER['HTTP_HOST']) . rtrim(dirname($_SERVER['PHP_SELF']), '/.\\') . '/') . "'");

        if (isset($this->request->get['store_id'])) {
            $this->config->set('config_store_id', (int)$this->request->get['store_id']);
        } else if ($query->num_rows) {
            $this->config->set('config_store_id', $query->row['store_id']);
        } else {
            $this->config->set('config_store_id', 0);
        }

        if (!$query->num_rows) {
            $this->config->set('config_url', HTTP_SERVER);
        }

        // Settings
        $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "setting` WHERE store_id = '0' OR store_id = '" . (int)$this->config->get('config_store_id') . "' ORDER BY store_id ASC");

        foreach ($query->rows as $result) {
            if (!$result['serialized']) {
                $this->config->set($result['key'], $result['value']);
            } else {
                $this->config->set($result['key'], json_decode($result['value'], true));
            }
        }

        // Theme
        $this->config->set('template_cache', $this->config->get('developer_theme'));

        // Url
        $this->registry->set('url', new Url($this->config->get('config_url')));

        // Language
        $code = '';
        $this->load->model('localisation/language');
        $languages = $this->model_localisation_language->getLanguages();
        $language_codes = array_column($languages, 'language_id', 'code');
        $auto_langs = $this->config->get('config_auto_langs') ?? []; //自动翻译支持语种
        $is_auto_trans = $auto_langs && $this->config->get('config_is_auto_translate') && $this->config->get('config_trans_api_url') ? true : false; //是否开启自动翻译
        $need_auto_trans = (isset($this->session->data['language']) && $is_auto_trans && in_array($this->session->data['language'], $auto_langs)) ? true : false;
        if (isset($this->session->data['language'])) {
            if (array_key_exists($this->session->data['language'], $language_codes) || $need_auto_trans) {
                $code = $this->session->data['language'];
            }
        }

        $need_auto_trans = ($is_auto_trans && !empty($this->request->cookie['language']) && in_array($this->request->cookie['language'], $auto_langs)) ? true : false;
        if (empty($code) && isset($this->request->cookie['language'])) {
            if (array_key_exists($this->request->cookie['language'], $language_codes) || $need_auto_trans) {
                $code = $this->request->cookie['language'];
            }
        }

        // Language Detection
        if (empty($code) && !empty($this->request->server['HTTP_ACCEPT_LANGUAGE']) && !empty($this->config->get('config_browser_auto_lang'))) {
            $detect = '';

            $browser_codes = array();

            $browser_languages = explode(',', strtolower($this->request->server['HTTP_ACCEPT_LANGUAGE']));

            // Try using local to detect the language
            foreach ($browser_languages as $browser_language) {
                $position = strpos($browser_language, ';q=');

                if ($position !== false) {
                    $browser_codes[][substr($browser_language, 0, $position)] = (float)substr($browser_language, $position + 3);
                } else {
                    $browser_codes[][$browser_language] = 1.0;
                }
            }

            $sort_order = array();

            foreach ($browser_codes as $key => $value) {
                $sort_order[$key] = $value[key($value)];
            }

            array_multisort($sort_order, SORT_ASC, $browser_codes);

            $browser_codes = array_reverse($browser_codes);

            foreach (array_values($browser_codes) as $browser_code) {
                $code_str = key($browser_code);
                if ($is_auto_trans && in_array($code_str, array_keys($this->config->get('support_langs')))) {
                    $detect = $code_str;
                } else {
                    foreach ($languages as $key => $value) {
                        if ($value['status']) {
                            $locale = explode(',', $value['locale']);
                            if (in_array($code_str, $locale)) {
                                $detect = $value['code'];
                                break 2;
                            }
                        }
                    }
                }
            }

            $code = ($detect) ? $detect : '';
        }

        if (!array_key_exists($code, $language_codes) && !$is_auto_trans) {
            $code = $this->config->get('config_language');
        }
        $in_local = true;
        //自动翻译检测在本地语言中
        if ($is_auto_trans) {
            $in_local = false;
            foreach ($languages as $key => $value) {
                if ($value['status']) {
                    $locale = explode(',', $value['locale']);
                    if (in_array($code, $locale)) {
                        $code = $value['code'];
                        $in_local = true;
                        break;
                    }
                }
            }
        }

        if (!isset($this->session->data['language']) || $this->session->data['language'] != $code) {
            $this->session->data['language'] = $code;
        }

        if (!isset($this->request->cookie['language']) || $this->request->cookie['language'] != $code) {
            setcookie('language', $code, time() + 60 * 60 * 24 * 30, '/', $this->request->server['HTTP_HOST']);
        }

        // Overwrite the default language object
        $final_code = isset($language_codes[$code]) ? $code : 'en-gb';
        $language = new Language($final_code);
        $language->load($final_code);

        $this->registry->set('language', $language);

        // Set the config language_id
        $this->config->set('config_language_id', $language_codes[$code] ?? $language_codes['en-gb']);
        $this->config->set('config_autotrans_inlocal', $in_local);
        // Translater
        $this->registry->set('translater', new Translater($this->config->get('translater_engine'), str_replace('&amp;', '&', $this->config->get('config_trans_api_url'))));

        // Customer
        $customer = new Cart\Customer($this->registry);
        $this->registry->set('customer', $customer);

        // Customer Group
        if (isset($this->session->data['customer']) && isset($this->session->data['customer']['customer_group_id'])) {
            // For API calls
            $this->config->set('config_customer_group_id', $this->session->data['customer']['customer_group_id']);
        } elseif ($this->customer->isLogged()) {
            // Logged in customers
            $this->config->set('config_customer_group_id', $this->customer->getGroupId());
        } elseif (isset($this->session->data['guest']) && isset($this->session->data['guest']['customer_group_id'])) {
            $this->config->set('config_customer_group_id', $this->session->data['guest']['customer_group_id']);
        }

        // Currency
        $code = '';

        $this->load->model('localisation/currency');

        $currencies = $this->model_localisation_currency->getCurrencies();

        if (isset($this->session->data['currency'])) {
            $code = $this->session->data['currency'];
        }

        if (isset($this->request->cookie['currency']) && !array_key_exists($code, $currencies)) {
            $code = $this->request->cookie['currency'];
        }

        if (!array_key_exists($code, $currencies)) {
            $code = $this->config->get('config_currency');
        }

        if (!isset($this->session->data['currency']) || $this->session->data['currency'] != $code) {
            $this->session->data['currency'] = $code;
        }

        if (!isset($this->request->cookie['currency']) || $this->request->cookie['currency'] != $code) {
            setcookie('currency', $code, time() + 60 * 60 * 24 * 30, '/', $this->request->server['HTTP_HOST']);
        }

        $this->registry->set('currency', new Cart\Currency($this->registry));

        // Tax
        $this->registry->set('tax', new Cart\Tax($this->registry));

        if (isset($this->session->data['shipping_address'])) {
            $this->tax->setShippingAddress($this->session->data['shipping_address']['country_id'], $this->session->data['shipping_address']['zone_id']);
        } elseif ($this->config->get('config_tax_default') == 'shipping') {
            $this->tax->setShippingAddress($this->config->get('config_country_id'), $this->config->get('config_zone_id'));
        }

        if (isset($this->session->data['payment_address'])) {
            $this->tax->setPaymentAddress($this->session->data['payment_address']['country_id'], $this->session->data['payment_address']['zone_id']);
        } elseif ($this->config->get('config_tax_default') == 'payment') {
            $this->tax->setPaymentAddress($this->config->get('config_country_id'), $this->config->get('config_zone_id'));
        }

        $this->tax->setStoreAddress($this->config->get('config_country_id'), $this->config->get('config_zone_id'));

        // Weight
        $this->registry->set('weight', new Cart\Weight($this->registry));

        // Length
        $this->registry->set('length', new Cart\Length($this->registry));

        // Cart
        $this->registry->set('cart', new Cart\Cart($this->registry));

        // Check
        $this->registry->set('check', new Cart\Check($this->registry));

        // Encryption
        $this->registry->set('encryption', new Encryption());

        //custom route
        if (!isset($this->request->get['route'])) {
            //自定义路由
            $customRoutes = require_once(DIR_APPLICATION . 'routes.php');
            if ($customRoutes) {
                $request_uri = strtolower($_SERVER["REQUEST_URI"]);
                $pattern = "/\{(.*?)\}/i";
                $replace_pattern = '(.*?)';
                foreach ($customRoutes as $request_key => $customRoute) {
                    if ($request_key == $request_uri) {
                        $this->request->get['route'] = $customRoute;
                    } else {
                        //匹配出控制器
                        $request_match = [];
                        $new_pat = preg_replace($pattern, $replace_pattern, $request_key);
                        $new_pat = "/" . str_replace('/', '\/', $new_pat) . "/i";
                        preg_match($new_pat, $request_uri, $request_match);
                        if ($request_match) {
                            $this->request->get['route'] = $customRoute;
                            //匹配出参数
                            preg_match_all($pattern, $request_key, $param_matches);
                            if ($param_matches && count($param_matches) >= 2) {
                                foreach ($param_matches[1] as $i => $request_key) {
                                    if (!empty($request_match[$i + 1])) {
                                        $this->request->get[$request_key] = $request_match[$i + 1];
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

    }
}
